package com.bmob.lover.app.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bmob.lover.app.util.CoverUtil;
import com.bmob.lover.data.model.bean.TheFile;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.qmuiteam.qmui.layout.QMUIRelativeLayout;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.utils.CommonUtil;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.NetworkUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;
import com.bmob.lover.R;
import com.bmob.lover.app.util.CoverUtil;
import com.bmob.lover.data.model.bean.TheFile;

import static android.widget.RelativeLayout.CENTER_IN_PARENT;
import static androidx.core.view.ViewKt.isVisible;
import static com.qmuiteam.qmui.widget.dialog.QMUIDialogAction.ACTION_PROP_POSITIVE;
import static com.theone.common.ext.ViewExtKt.goneViews;
import static com.theone.common.ext.ViewExtKt.invisibleViews;
import static com.theone.common.ext.ViewExtKt.showViews;

import static com.theone.mvvm.ext.qmui.QMUIDialogExtKt.showMsgDialog;;
/**
 * 带封面
 * Created by guoshuyu on 2017/9/3.
 */

public class SampleCoverVideo extends StandardGSYVideoPlayer {

    private static final String TAG = "SampleCoverVideo";
    private TheFile mFile;

    ImageView mCoverImage;

    String mCoverOriginUrl;

    private boolean isFirst = true;

    private int mWidth;
    private int mHeight;

    private ImageView ivPlay, ivDownload;

    public SampleCoverVideo(Context context, Boolean fullFlag) {
        super(context, fullFlag);
    }

    public SampleCoverVideo(Context context) {
        super(context);
    }

    public SampleCoverVideo(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void init(Context context) {
        super.init(context);
        ivPlay = findViewById(R.id.iv_play);
        ivDownload = findViewById(R.id.download_video);
        QMUIRelativeLayout qmuiRelativeLayout = findViewById(R.id.rl_container);
        qmuiRelativeLayout.setRadiusAndShadow(QMUIDisplayHelper.dp2px(context, 5), 0, 0);
        mCoverImage = (ImageView) findViewById(R.id.thumbImage);
        setViewShow(GONE, mBottomProgressBar);
        setViewShow(INVISIBLE, mBackButton, mBottomContainer);
        ivPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mIfCurrentIsFullscreen)
                    clickStartIcon();
                else
                    changeVolume();
            }
        });
        ivDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                download();
            }
        });
    }

    @Override
    protected void setStateAndUi(int state) {
        super.setStateAndUi(state);
        if (isVisible(mBottomContainer)) {
            goneViews(mStartButton);
            showViews(ivPlay);
        } else {
            showViews(mStartButton);
        }
        if (mIfCurrentIsFullscreen)
            updatePlayStatus();
        else{
            if(mCurrentState == CURRENT_STATE_PLAYING){
                showViews(ivPlay,mTotalTimeTextView);
            }else{
                invisibleViews(ivPlay,mTotalTimeTextView);
            }
            updateVolumeStatus();
        }
    }

    private void updatePlayStatus() {
        if (mCurrentState == CURRENT_STATE_PLAYING) {
            ivPlay.setImageResource(R.drawable.exo_icon_pause);
        } else {
            ivPlay.setImageResource(R.drawable.exo_icon_play);
        }
    }

    private void updateVolumeStatus() {
        ivPlay.setImageResource( GSYVideoManager.instance().isNeedMute() ?  R.drawable.ic_volume_close:R.drawable.ic_volume_open );
    }

    private void changeVolume() {
        GSYVideoManager.instance().setNeedMute(!GSYVideoManager.instance().isNeedMute());
        updateVolumeStatus();
    }

    @Override
    public int getLayoutId() {
        return R.layout.video_layout_cover;
    }

    public void loadCoverImage(TheFile file) {
        mFile = file;
        if (null == file || mWidth == 0) return;
        mCoverOriginUrl = file.getPath();
        if (!TextUtils.isEmpty(file.getMThumbnail()) && !file.getMThumbnail().equals(mCoverOriginUrl)) {
            mCoverOriginUrl = file.getMThumbnail();
            loadImage(file.getWidth(), file.getHeight());
        } else {
            Glide.with(mContext).asBitmap().load(mCoverOriginUrl).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
                    int width = bitmap.getWidth();
                    int height = bitmap.getHeight();
                    loadImage(width, height);
                }
            });
        }
    }

    private void loadImage(int width, int height) {
        if (width == 0) return;
        if (width > height) {
            width = mWidth;
            height = mHeight;
            mCoverImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
        } else {
            int[] size = CoverUtil.getAutoSize(width, height, mWidth);
            width = size[0];
            height = size[1];
        }
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
        params.addRule(CENTER_IN_PARENT);
        mCoverImage.setLayoutParams(params);
        Debuger.printfError("loadImage  width = " + width + "  height = " + height + "  coverUrl = " + mCoverOriginUrl);
        mCoverImage.layout(0, 0, width, height);

        Glide.with(getContext())
                .load(mCoverOriginUrl)
                .transition(new DrawableTransitionOptions().crossFade())// 渐入渐出效果
                .apply(new RequestOptions()
                        .placeholder(R.drawable.image_snap_loading_bg)
                        .override(width, height)
                        .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC))
                .into(mCoverImage);
        setViewShowState(mThumbImageViewLayout, VISIBLE);
        Debuger.printfError("loadImage  " + mFile.getImageUrl());
    }

    @Override
    protected void setProgressAndTime(int progress, int secProgress, int currentTime, int totalTime, boolean forceChange) {
        super.setProgressAndTime(progress, secProgress, currentTime, totalTime, forceChange);
        mProgressBar.setProgress(progress);
        mProgressBar.setSecondaryProgress(100);
        mTotalTimeTextView.setText(CommonUtil.stringForTime(totalTime - currentTime));
    }


    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        if (isFirst) {
            isFirst = false;
            mWidth = right - left;
            mHeight = bottom - top;
            loadCoverImage(mFile);
        }
        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected void resolveFullVideoShow(Context context, GSYBaseVideoPlayer gsyVideoPlayer, FrameLayout frameLayout) {
        super.resolveFullVideoShow(context, gsyVideoPlayer, frameLayout);
        Debuger.printfError("resolveFullVideoShow");
        setViewShow(VISIBLE, mProgressBar, ivPlay, ivDownload);
        updatePlayStatus();
        setViewShow(GONE, mStartButton);
    }

    @Override
    protected void resolveNormalVideoShow(View oldF, ViewGroup vp, GSYVideoPlayer gsyVideoPlayer) {
        super.resolveNormalVideoShow(oldF, vp, gsyVideoPlayer);
        Debuger.printfError("resolveNormalVideoShow");
        setViewShow(INVISIBLE, mProgressBar, mStartButton, ivPlay);
        setViewShow(GONE, mBackButton, ivDownload);
        if (mCurrentState == CURRENT_STATE_PAUSE) {
            setViewShow(VISIBLE, mStartButton);
            setViewShow(INVISIBLE, mTotalTimeTextView);
        } else if (mCurrentState == CURRENT_STATE_PLAYING) {
            updateVolumeStatus();
            setViewShow(VISIBLE, ivPlay);
        }
    }

    @Override
    protected void startDismissControlViewTimer() {

    }

    @Override
    protected void checkoutState() {
//        super.checkoutState();
    }

    /******************* 下方两个重载方法，在播放开始前不屏蔽封面，不需要可屏蔽 ********************/
    @Override
    public void onSurfaceUpdated(Surface surface) {
        super.onSurfaceUpdated(surface);
//        Debuger.printfError("onSurfaceUpdated");
//        ViewUtil.invisibleViews(mThumbImageViewLayout);
    }


    protected void setViewShow(int visibility, View... views) {
        for (View view : views) {
            setViewShowState(view, visibility);
        }
    }

    @Override
    protected void setViewShowState(View view, int visibility) {
        if (view == mBottomProgressBar) {
            mBottomProgressBar.setVisibility(GONE);
            return;
        }
        super.setViewShowState(view, visibility);
    }


    /******************* 下方重载方法，在播放开始不显示底部进度和按键，不需要可屏蔽 ********************/

    protected boolean byStartedClick;

    /**
     * 显示wifi确定框，如需要自定义继承重写即可
     */
    @Override
    protected void showWifiDialog() {
        if (!NetworkUtils.isAvailable(mContext)) {
            startPlayLogic();
            return;
        }
        showMsgDialog(mContext, "提示", getResources().getString(R.string.tips_not_wifi), getResources().getString(R.string.tips_not_wifi_cancel),
                getResources().getString(R.string.tips_not_wifi_confirm), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        startPlayLogic();
                    }
                },ACTION_PROP_POSITIVE);
    }

    @Override
    public void onClick(View v) {
        if (!mIfCurrentIsFullscreen && mCurrentState == CURRENT_STATE_PLAYING) {
            startWindowFullscreen(getContext(), false, true);
            return;
        }
        super.onClick(v);
    }

    @Override
    protected void onClickUiToggle(MotionEvent e) {
        if (mLockCurScreen && mNeedLockFull) {
            setViewShowState(mLockScreen, VISIBLE);
            return;
        }
        byStartedClick = true;
        if (mCurrentState == CURRENT_STATE_PLAYING) {
            Debuger.printfError("onClickUiToggle  CURRENT_STATE_PLAYING");
            if (mBottomContainer != null) {
                if (mBottomContainer.getVisibility() == View.VISIBLE) {
                    changeUiToPlayingClear();
                } else {
                    changeUiToPlayingShow();
                }
            }
            return;
        }
        super.onClickUiToggle(e);

    }

    @Override
    protected void changeUiToNormal() {
        Debuger.printfError("changeUiToNormal");
        super.changeUiToNormal();
        byStartedClick = false;
        setViewShow(GONE, mBackButton, ivDownload, mStartButton);
        setViewShow(INVISIBLE, mProgressBar);
        if (mCurrentState == CURRENT_STATE_PLAYING) {
            updateVolumeStatus();
            setViewShow(VISIBLE, ivPlay);
        }
    }

    @Override
    protected void changeUiToPreparingShow() {
        super.changeUiToPreparingShow();
        Debuger.printfError("Sample changeUiToPreparingShow");
//        setViewShowState(mBottomContainer, INVISIBLE);
        setViewShowState(mStartButton, INVISIBLE);
    }

    @Override
    protected void changeUiToPlayingBufferingShow() {
        super.changeUiToPlayingBufferingShow();
        Debuger.printfError("Sample changeUiToPlayingBufferingShow");
        if (!byStartedClick) {
//            setViewShowState(mBottomContainer, INVISIBLE);
            setViewShowState(mStartButton, INVISIBLE);
        }
    }

    @Override
    protected void changeUiToClear() {
        super.changeUiToClear();
        setViewShow(GONE, mBottomContainer);
    }

    @Override
    protected void changeUiToPlayingShow() {
        super.changeUiToPlayingShow();
        setViewShow(VISIBLE, mBottomContainer);
        Debuger.printfError("Sample changeUiToPlayingShow");
        setViewShowState(mStartButton, INVISIBLE);
    }

    @Override
    public void startAfterPrepared() {
        super.startAfterPrepared();
        Debuger.printfError("Sample startAfterPrepared");
//        setViewShowState(mBottomContainer, INVISIBLE);
        setViewShowState(mStartButton, INVISIBLE);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        byStartedClick = true;
        super.onStartTrackingTouch(seekBar);
    }

//    @Override
//    public boolean onLongClick(View v) {
//        if (!mIfCurrentIsFullscreen) {
//            return false;
//        }
//        List<String> list = new ArrayList<>();
//        list.add("下载");
//        QMUIBottomSheetUtil.showBottomListSheet(getContext(), list, "", -1, new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
//            @Override
//            public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
//
//                dialog.dismiss();
//            }
//        }).show();
//        return true;
//    }

    private void download() {
//        DownloadUtil.startDownload((Activity) getContext(), new ImageSnap() {
//            @Override
//            public String getImageUrl() {
//                return mUrl;
//            }
//
//            @Override
//            public String getThumbnail() {
//                return null;
//            }
//
//            @Override
//            public String getRefer() {
//                return null;
//            }
//
//            @Override
//            public boolean isVideo() {
//                return true;
//            }
//
//            @Override
//            public int getWidth() {
//                return 0;
//            }
//
//            @Override
//            public int getHeight() {
//                return 0;
//            }
//        });
    }
}
